package com.ruoyi.develop.projectBaseInfo.service.impl;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.goodsCustomer.domain.GoodsCustomer;
import com.ruoyi.develop.goodsCustomer.service.IGoodsCustomerService;
import com.ruoyi.develop.goodsFee.domain.GoodsFee;
import com.ruoyi.develop.goodsFee.service.impl.GoodsFeeServiceImpl;
import com.ruoyi.develop.goodsInvoiceApplyDetail.service.IGoodsInvoiceApplyDetailService;
import com.ruoyi.develop.goodsInvoiceInfo.domain.GoodsInvoiceInfo;
import com.ruoyi.develop.goodsInvoiceInfo.service.impl.GoodsInvoiceInfoServiceImpl;
import com.ruoyi.develop.goodsOrderIn.domain.GoodsOrderIn;
import com.ruoyi.develop.goodsOrderIn.mapper.GoodsOrderInMapper;
import com.ruoyi.develop.goodsSale.domain.GoodsSale;
import com.ruoyi.develop.goodsSale.mapper.GoodsSaleMapper;
import com.ruoyi.develop.goodsSaleChuan.domain.GoodsSaleChuan;
import com.ruoyi.develop.goodsSaleChuan.service.IGoodsSaleChuanService;
import com.ruoyi.develop.goodsSaledo.domain.GoodsSaledo;
import com.ruoyi.develop.goodsSaledo.mapper.GoodsSaledoMapper;
import com.ruoyi.develop.orderIronDetail.domain.OrderIronDetail;
import com.ruoyi.develop.orderIronDetail.service.IOrderIronDetailService;
import com.ruoyi.develop.orderIronGoods.domain.OrderIronGoods;
import com.ruoyi.develop.orderIronGoods.service.IOrderIronGoodsService;
import com.ruoyi.develop.orderIronRecord.domain.OrderIronRecord;
import com.ruoyi.develop.orderIronRecord.service.IOrderIronRecordService;
import com.ruoyi.develop.project.domain.Project;
import com.ruoyi.develop.project.mapper.ProjectMapper;
import com.ruoyi.develop.project.service.impl.ProjectServiceImpl;
import com.ruoyi.develop.projectBaseInfo.domain.ProjectBaseInfo;
import com.ruoyi.develop.projectBaseInfo.mapper.ProjectBaseInfoMapper;
import com.ruoyi.develop.projectBaseInfo.service.IProjectBaseInfoService;
import com.ruoyi.export.service.impl.ExportServiceImpl;
import com.ruoyi.system.mapper.SysUserMapper;
import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.ss.usermodel.DateUtil;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.ruoyi.system.service.ISysUserService;

/**
 * 项目基础信息管理Service业务层处理
 *
 * @author qh
 * @date 2023-01-10
 */
@Service
public class ProjectBaseInfoServiceImpl implements IProjectBaseInfoService {
    @Resource
    private ProjectBaseInfoMapper projectBaseInfoMapper;
    @Resource
    private ProjectServiceImpl projectService;
    @Resource
    private GoodsSaleMapper goodsSaleMapper;
    @Resource
    private GoodsOrderInMapper goodsOrderInMapper;

    /*@Resource
    private ProjectInvoiceInfoMapper invoiceInfoMapper;
    @Resource
    private ProjectFundBackMapper fundBackMapper;*/
    @Resource
    private GoodsFeeServiceImpl feeService;
    @Resource
    private GoodsInvoiceInfoServiceImpl invoiceInfoService;
    @Resource
    private ISysUserService iSysUserService;
    @Resource
    private IGoodsCustomerService iGoodsCustomerService;
    @Resource
    private IOrderIronRecordService orderIronRecordService;
    @Resource
    private IOrderIronDetailService orderIronDetailService;

    @Resource
    private IGoodsInvoiceApplyDetailService invoiceApplyDetailService;

    @Resource
    private IOrderIronGoodsService orderIronGoodsService;
    @Resource
    private IGoodsSaleChuanService goodsSaleChuanService;
    @Autowired
    private ExportServiceImpl exportService;
    @Resource
    private GoodsSaledoMapper goodsSaledoMapper;


    @Resource
    private SysUserMapper sysUserMapper;

    @Value(value = "${ruoyi.path}")
    public String basePath;
    @Value(value = "${ruoyi.templatePath}")
    public String templatePath;
    @Value(value = "${ruoyi.templateImport}")
    public String templateImport;

    /**
     * 查询项目基础信息管理
     *
     * @param id 项目基础信息管理主键
     * @return 项目基础信息管理
     */
    @Override
    public ProjectBaseInfo selectById(String id) {
        return projectBaseInfoMapper.selectById(id);
    }

    @Override
    public void updateStatus(String status,String id) {
         projectBaseInfoMapper.updateStatus(status,id);
    }
    @Override
    public ProjectBaseInfo listCount() {
        return projectBaseInfoMapper.listCount();
    }

    @Override
    public ProjectBaseInfo listMoney() {
        return projectBaseInfoMapper.listMoney();
    }
    /**
     * 查询项目基础信息管理列表
     *
     * @param entity 项目基础信息管理
     * @return 项目基础信息管理
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<ProjectBaseInfo> selectList(ProjectBaseInfo entity) {
        return projectBaseInfoMapper.selectList(entity);
    }

    @Override
    @DataScope(deptAlias = "d")
    public List<ProjectBaseInfo> listNotTiejian(ProjectBaseInfo entity) {
        return projectBaseInfoMapper.listNotTiejian(entity);
    }

    @Override
    @DataScope(deptAlias = "d")
    public List<ProjectBaseInfo> listNotAllKp(ProjectBaseInfo entity) {
        return projectBaseInfoMapper.listNotAllKp(entity);
    }

    @Override
    public List<ProjectBaseInfo> listByAreaGroup(ProjectBaseInfo entity) {
        return projectBaseInfoMapper.listByAreaGroup(entity);
    }


    @Override
    public List<ProjectBaseInfo> listByStatusGroup(ProjectBaseInfo entity) {
        return projectBaseInfoMapper.listByStatusGroup(entity);
    }

    @Override
    public List<ProjectBaseInfo> listBySourceGroup(ProjectBaseInfo entity) {
        return projectBaseInfoMapper.listBySourceGroup(entity);
    }

    @Override
    public List<ProjectBaseInfo> listByYearGroup(ProjectBaseInfo entity) {
        return projectBaseInfoMapper.listByYearGroup(entity);
    }

    @Override
    public List<ProjectBaseInfo> selectListNoScope(ProjectBaseInfo entity) {
        return projectBaseInfoMapper.selectList(entity);
    }

    /**
     * 新增项目基础信息管理
     *
     * @param entity 项目基础信息管理
     * @return 结果
     */
    @Override
    public int insert(ProjectBaseInfo entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        if (StringUtils.isNotBlank(entity.getSalesmanId())) {
            SysUser sysUser = sysUserMapper.selectUserById(entity.getSalesmanId());
            entity.setSalesmanName(sysUser.getUserName());
        }
        if (StringUtils.isNotBlank(entity.getProjectId())) {
            Project project = projectService.selectById(entity.getProjectId());
            entity.setProjectCode(project.getCode());
        }

        if (StringUtils.isNotBlank(entity.getCustomId())) {
            GoodsCustomer goodsCustomer = iGoodsCustomerService.selectById(entity.getCustomId());
            entity.setCustomName(goodsCustomer.getName());
            entity.setCustomerCode(goodsCustomer.getCode());
        }

        if (entity.getContractMoney() != null && entity.getContractMoney().compareTo(BigDecimal.ZERO) > 0) {
            entity.setTaxAll(BigDecimal.ZERO); //已开票总金额
            entity.setTaxRemain(entity.getContractMoney());
            entity.setBackMoney(BigDecimal.ZERO);
            entity.setRemainMoney(entity.getContractMoney());
        }
        // 如果回款日期不为空 计算出 回款天数
        if (entity.getEndDate() != null) {
            entity.setReturnDays(DateUtils.getDaysCountBetween2Date(entity.getContractDate(), entity.getEndDate()));
        }
        return projectBaseInfoMapper.insert(entity);
    }

    @Override
    public String checkCodeUnique(String code) {
        int count = projectBaseInfoMapper.checkCodeUnique(code);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 修改项目基础信息管理
     *
     * @param entity 项目基础信息管理
     * @return 结果
     */
    @Override
    public int update(ProjectBaseInfo entity) {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());

        if (StringUtils.isNotBlank(entity.getSalesmanId())) {
            SysUser sysUser = sysUserMapper.selectUserById(entity.getSalesmanId());
            entity.setSalesmanName(sysUser.getUserName());
        }
        if (StringUtils.isNotBlank(entity.getCustomId())) {
            GoodsCustomer goodsCustomer = iGoodsCustomerService.selectById(entity.getCustomId());
            entity.setCustomName(goodsCustomer.getName());
            entity.setCustomerCode(goodsCustomer.getCode());
        }
        if (StringUtils.isNotBlank(entity.getProjectId())) {
            Project project = projectService.selectById(entity.getProjectId());
            entity.setProjectCode(project.getCode());
        }

        if (entity.getContractMoney() != null && entity.getContractMoney().compareTo(BigDecimal.ZERO) > 0) {
            // 剩余开票金额 = 开票总金额 - 已开票金额
            BigDecimal totalTax = invoiceApplyDetailService.selectSumTaxByProjectId(entity.getId());
            entity.setTaxAll(totalTax);
            entity.setTaxRemain(entity.getContractMoney().subtract(totalTax));

            // 回款金额 = 订单金额 - 回款金额
            BigDecimal totalBack = invoiceApplyDetailService.selectSumBackMoneyByProjectId(entity.getId());
            entity.setBackMoney(totalBack);
            entity.setRemainMoney(entity.getContractMoney().subtract(totalBack));

        }
        // 如果回款日期不为空 计算出 回款天数
        if (entity.getEndDate() != null) {
            entity.setReturnDays(DateUtils.getDaysCountBetween2Date(entity.getContractDate(), entity.getEndDate()));
        }
        GoodsSale goodsSale=new GoodsSale();
        goodsSale.setProjectId(entity.getId());
        List<GoodsSale> goodsSaleList= goodsSaleMapper.listByProjectId(goodsSale);
        for(GoodsSale goodsSale1:goodsSaleList){
            goodsSale1.setProjectNo(entity.getCode());
            goodsSale1.setProjectName(entity.getName());
            goodsSaleMapper.update(goodsSale1);
        }
        GoodsSaledo goodsSaledo=new GoodsSaledo();
        goodsSaledo.setProjectId(entity.getId());
        List<GoodsSaledo> goodsSaledos=goodsSaledoMapper.listByProjectId(goodsSaledo);
        for(GoodsSaledo goodsSaledo1:goodsSaledos){
            goodsSaledo1.setProjectNo(entity.getCode());
            goodsSaledo1.setProjectName(entity.getName());
            goodsSaledoMapper.update(goodsSaledo1);
        }
        return projectBaseInfoMapper.update(entity);
    }

    @Override
    public int updateBackMoney(ProjectBaseInfo entity) {
        try {
            entity.setCreateBy(SecurityUtils.getUsername());
        } catch (Exception e) {
            entity.setCreateBy("auto");
        }
        entity.setUpdateTime(DateUtils.getNowDate());

        if (StringUtils.isNotBlank(entity.getSalesmanId())) {
            SysUser sysUser = sysUserMapper.selectUserById(entity.getSalesmanId());
            entity.setSalesmanName(sysUser.getUserName());
        }
        if (StringUtils.isNotBlank(entity.getCustomId())) {
            GoodsCustomer goodsCustomer = iGoodsCustomerService.selectById(entity.getCustomId());
            entity.setCustomName(goodsCustomer.getName());
            entity.setCustomerCode(goodsCustomer.getCode());
        }
        if (StringUtils.isNotBlank(entity.getProjectId())) {
            Project project = projectService.selectById(entity.getProjectId());
            entity.setProjectCode(project.getCode());
        }

        // 如果回款日期不为空 计算出 回款天数
        if (entity.getEndDate() != null) {
            entity.setReturnDays(DateUtils.getDaysCountBetween2Date(entity.getContractDate(), entity.getEndDate()));
        }
        return projectBaseInfoMapper.update(entity);
    }


    /**
     * 批量删除项目基础信息管理
     *
     * @param ids 需要删除的项目基础信息管理主键
     * @return 结果
     */
    @Override
    public int deleteByIds(String[] ids) {

        // 删除订单后 删除订单产品
        for (String projectId : ids) {
            goodsSaleMapper.deleteByProjectId(projectId);
            orderIronRecordService.deleteByProjectId(projectId);
        }



        return projectBaseInfoMapper.deleteByIds(ids);
    }

    /**
     * 删除项目基础信息管理信息
     *
     * @param id 项目基础信息管理主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return projectBaseInfoMapper.deleteById(id);
    }

    @Override
    public List<SysDictData> selectAllProject(ProjectBaseInfo param) {
        List<SysDictData> dictDatas = new ArrayList<>();
        List<ProjectBaseInfo> lists = selectList(param);
        lists.stream().forEach(entity -> {
            SysDictData dict = new SysDictData();
            dict.setLabel(entity.getCode());
            dict.setValue(entity.getId());
            dict.setRemark(entity.getCode());
            dict.setDictValue(entity.getCustomId());
            dict.setDictLabel(entity.getCustomName());
            Map<String, Object> map = new HashMap<>();
            map.put("taxRemain", entity.getTaxRemain());
            map.put("contactMoney", entity.getContractMoney());
            map.put("taxNo", entity.getTaxcode());
            map.put("salesmanName", entity.getSalesmanName());
            map.put("salesmanId", entity.getSalesmanId());
            dict.setParams(map);
            dictDatas.add(dict);
        });
        return dictDatas;
    }

    @Override
    public AjaxResult refreshProfit(ProjectBaseInfo projectBaseInfo) {
        String projectId = projectBaseInfo.getId();
        projectBaseInfo = selectById(projectId);
        GoodsSale saleParam = new GoodsSale();
        saleParam.setProjectId(projectId);
        List<GoodsSale> saleList = goodsSaleMapper.selectList(saleParam);
        final BigDecimal[] saleMoney = {BigDecimal.ZERO};
        final BigDecimal[] buyMoney = {BigDecimal.ZERO};
        final BigDecimal[] feeMoney = {BigDecimal.ZERO};
        saleList.stream().forEach(saleInfo -> {
            if (BusinessConstants.TYPE_PROJECT.equals(saleInfo.getType())) {
                saleMoney[0] = saleMoney[0].add(saleInfo.getGoodsTotalPrice());
                buyMoney[0] = buyMoney[0].add(saleInfo.getGoodsBuyTotal());
            } else if (BusinessConstants.TYPE_PROJECT_FEE.equals(saleInfo.getType())) {
//                feeMoney[0] = feeMoney[0].add(saleInfo.getGoodsTotalPrice());
            }
        });
        //合计并更新费用
        GoodsFee param = new GoodsFee();
        param.setProId(projectId);
        List<GoodsFee> feeList = feeService.selectList(param);
        feeList.stream().forEach(fee -> {
            feeMoney[0] = feeMoney[0].add(fee.getMoney());
        });

        projectBaseInfo.setSaleMoney(saleMoney[0]);
        projectBaseInfo.setBuyMoney(buyMoney[0]);
        projectBaseInfo.setFeeMoney(feeMoney[0]);

        update(projectBaseInfo);
        return AjaxResult.success("更新成功");
    }

    @Override
    public Map<String, Object> getExportData(String id) {
        Map<String, Object> resMap = new HashedMap();
        ProjectBaseInfo project = selectById(id);
        Map<String, Object> map1 = new HashedMap();
        map1.put("contractDate", DateUtils.formatDate(project.getContractDate(), DateUtils.YYYY_MM_DD));
        project.setParams(map1);
        project.setFundCallback(DictUtils.getDictLabel("yes_no", project.getFundCallback()));
        //销售及费用
        GoodsSale saleP = new GoodsSale();
        saleP.setProjectId(id);
        List<GoodsSale> sales = goodsSaleMapper.selectList(saleP);
        //费用
        List<GoodsSale> projectFee = sales.stream().filter(sale -> {
            return sale.getType().equals(BusinessConstants.TYPE_PROJECT_FEE);
        }).collect(Collectors.toList());
        projectFee.stream().forEach(item -> {
            Map<String, Object> map2 = new HashedMap();
            map2.put("saleDate", DateUtils.formatDate(item.getSaleDate(), DateUtils.YYYY_MM_DD));
            item.setParams(map2);
        });
        //销售
        List<GoodsSale> projectSale = sales.stream().filter(sale -> {
            return sale.getType().equals(BusinessConstants.TYPE_PROJECT);
        }).collect(Collectors.toList());
        projectSale.stream().forEach(item -> {
            Map<String, Object> map3 = new HashedMap();
            map3.put("saleDate", DateUtils.formatDate(item.getSaleDate(), DateUtils.YYYY_MM_DD));
            item.setParams(map3);
        });
        //TODO 开票20231205
        /*ProjectInvoiceInfo invoiceP = new ProjectInvoiceInfo();
        invoiceP.setProjectId(id);
        List<ProjectInvoiceInfo> invoiceInfos = invoiceInfoMapper.selectList(invoiceP);
        invoiceInfos.stream().forEach(item -> {
            Map<String, Object> map4 = new HashedMap();
            map4.put("invoiceDate", DateUtils.formatDate(item.getInvoiceDate(), DateUtils.YYYY_MM_DD));
            item.setParams(map4);
            item.setStatus(DictUtils.getDictLabel("fund_callback", item.getStatus()));
        });*/
        //TODO 回款20231205
        /*ProjectFundBack fundBackP = new ProjectFundBack();
        fundBackP.setProjectId(id);
        List<ProjectFundBack> fundBacks = fundBackMapper.selectList(fundBackP);
        fundBacks.stream().forEach(item -> {
            Map<String, Object> map5 = new HashedMap();
            map5.put("backDate", DateUtils.formatDate(item.getBackDate(), DateUtils.YYYY_MM_DD));
            item.setParams(map5);
        });*/

        resMap.put("entity", project);//项目基础信息
        resMap.put("projectFee", projectFee);//项目费用
        resMap.put("projectSale", projectSale);//项目销售
//        resMap.put("invoiceInfos", invoiceInfos);//项目发票
//        resMap.put("fundBacks", fundBacks);//项目发票

        return resMap;
    }

    /*
     * 重新计算项目开票信息及状态
     * */
    @Override
    public void updateProjectTaxInfo(String projectId) {
        GoodsInvoiceInfo invoiceParam = new GoodsInvoiceInfo();
        invoiceParam.setProjectId(projectId);
        List<GoodsInvoiceInfo> invoices = invoiceInfoService.selectList(invoiceParam);
        BigDecimal allMoney = BigDecimal.ZERO;
        for (GoodsInvoiceInfo invoice : invoices) {
            if (invoice.getInvoiceMoney() != null) {
                allMoney = invoice.getInvoiceMoney().add(allMoney);
            }
        }
        String[] proId = projectId.split(",");
        //批量修改项目开票金额
        for (String pid : proId) {
            if (StringUtils.isNotEmpty(proId)) {
                ProjectBaseInfo projectBaseInfo = selectById(pid);
                if (projectBaseInfo != null) {
                    if (projectBaseInfo.getContractMoney().compareTo(allMoney) > 0) {
                        projectBaseInfo.setTaxAll(allMoney);
                        projectBaseInfo.setTaxRemain(projectBaseInfo.getContractMoney().subtract(allMoney));
                        projectBaseInfo.setTaxStatus(BusinessConstants.TAX_STATUS_1);
                    } else if (projectBaseInfo.getContractMoney().compareTo(allMoney) == 0) {
                        projectBaseInfo.setTaxAll(allMoney);
                        projectBaseInfo.setTaxRemain(projectBaseInfo.getContractMoney().subtract(allMoney));
                        projectBaseInfo.setTaxStatus(BusinessConstants.TAX_STATUS_2);
                    } else {
                        projectBaseInfo.setTaxAll(projectBaseInfo.getContractMoney());
                        projectBaseInfo.setTaxRemain(BigDecimal.ZERO);
                    }
                    update(projectBaseInfo);
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Map<String, Object> importData(ProjectBaseInfo contact, MultipartFile file) {
        String tmplName = "projectBaseInfo.xml";
        String errortext = "";
        Map<String, Object> map = new HashMap<>();
        int i = 0;
        int j = 0;
        try {
            // InputStream in = resource.getInputStream();
            InputStream in = new FileInputStream(basePath + File.separator
                    + templatePath + File.separator + templateImport + File.separator + tmplName);
            XLSReader mainReader = ReaderBuilder.buildFromXML(in);

            List<ProjectBaseInfo> list = new ArrayList<>();
            List<ProjectBaseInfo> list1 = new ArrayList<>();


            Map beans = new HashMap();
            beans.put("list", list);
            XLSReadStatus readStatus = mainReader.read(file.getInputStream(), beans);
            if (readStatus.isStatusOK()) {
                for (ProjectBaseInfo info : list) {
                    ProjectBaseInfo entity = new ProjectBaseInfo();
                    entity.setId(IdUtils.fastSimpleUUID());
                    BeanUtils.copyProperties(info, entity, "id");
                    if (StringUtils.isNotBlank(info.getIdx())) if (StringUtils.isNotBlank(info.getCode())) {

                        String code = info.getParams().get("code") != null ? info.getParams().get("code").toString() : "";
                        if (StringUtils.isBlank(code)) {
                            errortext += "序号为" + info.getIdx() + "行数据，框架编号不能为空，请填写后导入！";
                        } else {
                            Project project = projectService.selectProjectByCode(code);
                            if (project == null) {
                                errortext += "序号为" + info.getIdx() + "行数据，框架编号不存在，请填写后导入！";
                            } else {
                                entity.setProject(project);
                                entity.setProjectId(project.getId());
                            }
                        }

                        if (StringUtils.isBlank(info.getName())) {
                            errortext += "序号为" + info.getIdx() + "行数据，订单名称不能为空，请填写后导入！";
                        }
                        if (StringUtils.isBlank(info.getSalesmanName())) {
                            errortext += "序号为" + info.getIdx() + "行数据，订单业务员不能为空，请填写后导入！";
                        } else {
                            SysUser sysUser = iSysUserService.selectUserByUserName(info.getSalesmanName());
                            if (sysUser != null) {
                                entity.setSalesmanId(sysUser.getUserId());
                                entity.setDeptId(sysUser.getDeptId());
                                entity.setDeptName(sysUser.getDept().getDeptName());
                            } else {
                                errortext += "序号为" + info.getIdx() + "行数据，订单业务员不存在，请检查后导入！";
                            }
                        }
                        if (StringUtils.isBlank(info.getCustomName())) {
                            errortext += "序号为" + info.getIdx() + "行数据，客户名称不能为空，请填写后导入！";
                        } else {
                            GoodsCustomer goodsCustomer = iGoodsCustomerService.selectByName(info.getCustomName());
                            if (goodsCustomer != null) {
                                entity.setCustomId(goodsCustomer.getId());
                            } else {
                                errortext += "序号为" + info.getIdx() + "行数据，客户不存在，请检查后导入！";
                            }
                        }
//                        if (StringUtils.isBlank(info.getContractMoneyStr())) {
//                            errortext += "序号为" + info.getIdx() + "行数据，订单金额不能为空，请填写后导入！";
//                        } else {
//                            boolean isNumber = Pattern.matches("[0-9.]+", info.getContractMoneyStr());
//                            if (isNumber) {
//                                entity.setContractMoney(new BigDecimal(info.getContractMoneyStr()));
//                                entity.setTaxRemain(new BigDecimal(info.getContractMoneyStr()));
//                            } else {
//                                errortext += "序号为" + info.getIdx() + "行数据，订单金额输入不正确，请检查后重新输入！";
//                            }
//                        }
                        if (StringUtils.isNotBlank(info.getCode())) {
                            try {
                                Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");
                                Matcher isNum = pattern.matcher(info.getContractDateStr());
                                if (!isNum.matches()) {
                                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                    entity.setContractDate(df.parse(info.getContractDateStr()));
                                } else {
                                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                    String date = df.format(DateUtil.getJavaDate(Double.parseDouble(info.getContractDateStr())));
                                    entity.setContractDate(DateUtils.parseDate(date, "yyyy-MM-dd"));
                                }
                            } catch (Exception e) {
                                errortext += "序号为第" + info.getIdx() + "行数据，初次救助项目入机构时间格式错误，请规定的日期格式进行修改！";
                                e.printStackTrace();
                            }
                        }
                        Calendar calendar = Calendar.getInstance();
                        entity.setYear(String.valueOf(calendar.get(Calendar.YEAR)));

                        if (StringUtils.isNotBlank(errortext)) {
                            map.put("errorText", errortext);
                            map.put("num", i);
                            map.put("numupdate", i);
                            return map;

                        } else {
                            list1.add(entity);
                        }
                    } else {
                        errortext += "序号为" + info.getIdx() + "行数据，订单编号不能为空，请填写后导入！";
                    }
                }
            }
            if (StringUtils.isBlank(errortext)) {
                for (ProjectBaseInfo info : list1) {
                    ProjectBaseInfo projectBaseInfo = new ProjectBaseInfo();
                    projectBaseInfo.setCode(info.getCode());
                    List<ProjectBaseInfo> contactList = projectBaseInfoMapper.selectList(projectBaseInfo);
                    if (contactList.size() > 0) {
                        // info=contactList.get(0);
                        info.setId(contactList.get(0).getId());
                        j += this.update(info);
                    } else {
                        i += this.insert(info);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("errorText", errortext);
        map.put("num", i);
        map.put("numupdate", j);
        return map;
    }

    @Override
    public ProjectBaseInfo selectByCode(String code) {
        return projectBaseInfoMapper.selectByCode(code);
    }


    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Map<String, Object> importOrderAndGoodsData(ProjectBaseInfo contact, MultipartFile file) {
        String tmplName = "projectBaseInfoAndGoods.xml";
        String errortext = "";
        Map<String, Object> map = new HashMap<>();
        int orderInsertCount = 0;
        int orderUpdateCount = 0;
        int goodsInsertCount = 0;
        int goodsUpdateCount = 0;
        map.put("orderInsertCount", orderInsertCount);
        map.put("orderUpdateCount", orderUpdateCount);
        map.put("goodsInsertCount", goodsInsertCount);
        map.put("goodsUpdateCount", goodsUpdateCount);


        try {
            InputStream in = new FileInputStream(basePath + File.separator
                    + templatePath + File.separator + templateImport + File.separator + tmplName);
            XLSReader mainReader = ReaderBuilder.buildFromXML(in);

            List<ProjectBaseInfo> list = new ArrayList<>();
            List<ProjectBaseInfo> distinctList = new ArrayList<>();
            List<ProjectBaseInfo> list1 = new ArrayList<>();

            Map beans = new HashMap();
            beans.put("list", list);
            XLSReadStatus readStatus = mainReader.read(file.getInputStream(), beans);
            if (readStatus.isStatusOK()) {

                for (ProjectBaseInfo info : list) {
                    ProjectBaseInfo entity = new ProjectBaseInfo();
                    entity.setId(IdUtils.fastSimpleUUID());
                    BeanUtils.copyProperties(info, entity, "id");
                    if (StringUtils.isNotBlank(info.getIdx())) {
                        if (StringUtils.isNotBlank(info.getCode())) {
                            String code = info.getParams().get("code") != null ? info.getParams().get("code").toString().trim() : "";
                            if (StringUtils.isBlank(code)) {
                                errortext += "序号为" + info.getIdx() + "行数据，框架编号不能为空，请填写后导入！";
                            } else {
                                Project project = projectService.selectProjectByCode(code);
                                if (project == null) {
                                    errortext += "序号为" + info.getIdx() + "行数据，框架编号不存在，请填写后导入！";
                                } else {
                                    entity.setProject(project);
                                    entity.setProjectId(project.getId());
                                }
                            }

                            if (StringUtils.isBlank(info.getGoodsType())) {
                                errortext += "序号为" + info.getIdx() + "行数据，订单产品类别不能为空，请填写后导入！";
                            } else {
                                entity.setGoodsType(DictUtils.getDictValue("order_goods_type", info.getGoodsType()));
                            }

                            if (StringUtils.isBlank(info.getCode())) {
                                errortext += "序号为" + info.getIdx() + "行数据，订单编号不能为空，请填写后导入！";
                            } else {
                                ProjectBaseInfo projectBaseInfo = projectBaseInfoMapper.selectByCode(info.getCode());
                                if (projectBaseInfo != null) {
                                    errortext += "序号为" + info.getIdx() + "行数据，订单在系统中已经存在，请检查后导入！";
                                } else {

                                }
                            }

                            if (StringUtils.isBlank(info.getCreateName())) {
                                errortext += "序号为" + info.getIdx() + "行数据，制单人不能为空，请填写后导入！";
                            } else {
                                SysUser sysUser = iSysUserService.selectUserByUserName(info.getCreateName().trim());
                                if (sysUser != null) {
                                    entity.setCreateName(sysUser.getNickName());
                                } else {
                                    errortext += "序号为" + info.getIdx() + "行数据，制单人不存在，请检查后导入！";
                                }
                            }

                            if (StringUtils.isBlank(info.getSalesmanName())) {
                                errortext += "序号为" + info.getIdx() + "行数据，订单业务员不能为空，请填写后导入！";
                            } else {
                                SysUser sysUser = iSysUserService.selectUserByUserName(info.getSalesmanName().trim().replace("\n", "").replace("\r", ""));
                                if (sysUser != null) {
                                    entity.setSalesmanId(sysUser.getUserId());
                                    entity.setDeptId(sysUser.getDeptId());
                                    entity.setDeptName(sysUser.getDept().getDeptName());
                                } else {
                                    errortext += "序号为" + info.getIdx() + "行数据，订单业务员不存在，请检查后导入！";
                                }
                            }
                            if (StringUtils.isBlank(info.getCustomerCode())) {
                                errortext += "序号为" + info.getIdx() + "行数据，买方编码不能为空，请填写后导入！";
                            } else {
                                GoodsCustomer goodsCustomer = iGoodsCustomerService.selectByCode(info.getCustomerCode().replace("\n", "").replace("\r", ""));
                                if (goodsCustomer != null) {
                                    entity.setCustomId(goodsCustomer.getId());
                                    entity.setCustomName(goodsCustomer.getName());
                                    entity.setTaxcode(goodsCustomer.getTaxNo());
                                } else {
                                    errortext += "序号为" + info.getIdx() + "行数据，买方编码不存在，请检查后导入！";
                                }
                            }

                            if (StringUtils.isNotBlank(info.getContractDateStr())) {
                                try {
                                    Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");
                                    Matcher isNum = pattern.matcher(info.getContractDateStr());
                                    if (!isNum.matches()) {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        entity.setContractDate(df.parse(info.getContractDateStr()));
                                    } else {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        String date = df.format(DateUtil.getJavaDate(Double.parseDouble(info.getContractDateStr())));
                                        entity.setContractDate(DateUtils.parseDate(date, "yyyy-MM-dd"));
                                    }
                                } catch (Exception e) {
                                    errortext += "序号为第" + info.getIdx() + "行数据，订单签订时间格式错误，请规定的日期格式进行修改！";
                                    e.printStackTrace();
                                }
                            }

                            String deliveryTime = info.getParams().get("deliveryTime") != null ? info.getParams().get("deliveryTime").toString() : "";
                            deliveryTime = deliveryTime.replace("\n", "").replace("\r", "");
                            if (StringUtils.isNotBlank(deliveryTime)) {
                                try {
                                    Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");
                                    Matcher isNum = pattern.matcher(deliveryTime);
                                    if (!isNum.matches()) {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        entity.setDeliveryTime(df.parse(deliveryTime));
                                    } else {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        String date = df.format(DateUtil.getJavaDate(Double.parseDouble(deliveryTime)));
                                        entity.setDeliveryTime(DateUtils.parseDate(date, "yyyy-MM-dd"));
                                    }
                                } catch (Exception e) {
                                    errortext += "序号为第" + info.getIdx() + "行数据，合同到货时间格式错误，请规定的日期格式进行修改！";
                                    e.printStackTrace();
                                }
                            }

                            String orderDate = info.getParams().get("orderDate") != null ? info.getParams().get("orderDate").toString() : "";
                            orderDate = orderDate.replace("\n", "").replace("\r", "");
                            if (StringUtils.isNotBlank(orderDate)) {
                                try {
                                    Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");
                                    Matcher isNum = pattern.matcher(orderDate);
                                    if (!isNum.matches()) {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        entity.setOrderDate(df.parse(orderDate));
                                    } else {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        String date = df.format(DateUtil.getJavaDate(Double.parseDouble(orderDate)));
                                        entity.setOrderDate(DateUtils.parseDate(date, "yyyy-MM-dd"));
                                    }
                                } catch (Exception e) {
                                    errortext += "序号为第" + info.getIdx() + "行数据，下单日期格式错误，请规定的日期格式进行修改！";
                                    e.printStackTrace();
                                }
                            }

                            String goodsCode = info.getParams().get("goodsCode") != null ? info.getParams().get("goodsCode").toString() : "";
                            goodsCode = goodsCode.replace("\n", "").replace("\r", "");
                            if (StringUtils.isBlank(goodsCode)) {
                                errortext += "序号为第" + info.getIdx() + "行数据，商品编码不能为空！";
                            } else {
                                GoodsOrderIn goods = goodsOrderInMapper.selectByCode(goodsCode);
                                if (goods == null) {
                                    errortext += "序号为" + info.getIdx() + "行数据，存货编码不存在，请检查后导入！";
                                } else if (!BusinessConstants.ASSESS_STATUS_PASS.equals(goods.getAssessStatus())) {
                                    errortext += "序号为" + info.getIdx() + "行数据，存货编码未审核通过，请检查后导入！";
                                } else {
                                    entity.setGoods(goods);
                                }
                            }

                            String goodsCounts = info.getParams().get("goodsCounts") != null ? info.getParams().get("goodsCounts").toString() : "";
                            goodsCounts = goodsCounts.replace("\n", "").replace("\r", "");
                            if (StringUtils.isBlank(goodsCounts)) {
                                errortext += "序号为第" + info.getIdx() + "行数据，商品数量不能为空！";
                            }
                            String goodsUnitPrice = info.getParams().get("goodsUnitPrice") != null ? info.getParams().get("goodsUnitPrice").toString() : "";
                            goodsUnitPrice = goodsUnitPrice.replace("\n", "").replace("\r", "");
                            if (StringUtils.isBlank(goodsUnitPrice)) {
                                errortext += "序号为第" + info.getIdx() + "行数据，商品单价不能为空！";
                            }
                            String goodsTotalPrice = info.getParams().get("goodsTotalPrice") != null ? info.getParams().get("goodsTotalPrice").toString() : "";
                            goodsTotalPrice = goodsTotalPrice.replace("\n", "").replace("\r", "");
                            if (StringUtils.isBlank(goodsTotalPrice)) {
                                errortext += "序号为第" + info.getIdx() + "行数据，商品总价不能为空！";
                            }
                            String goodsTaxUnitPrice = info.getParams().get("goodsTaxUnitPrice") != null ? info.getParams().get("goodsTaxUnitPrice").toString() : "";
                            goodsTaxUnitPrice = goodsTaxUnitPrice.replace("\n", "").replace("\r", "");
                            if (StringUtils.isBlank(goodsTaxUnitPrice)) {
                                errortext += "序号为第" + info.getIdx() + "行数据，商品含税单价不能为空！";
                            }
                            String goodsTaxTotalPrice = info.getParams().get("goodsTaxTotalPrice") != null ? info.getParams().get("goodsTaxTotalPrice").toString() : "";
                            if (StringUtils.isBlank(goodsTaxTotalPrice)) {
                                errortext += "序号为第" + info.getIdx() + "行数据，商品含税总价不能为空！";
                            }
                            String area = info.getArea();
                            area = area.replace("\n", "").replace("\r", "");
                            if (StringUtils.isBlank(area) || StringUtils.isBlank(DictUtils.getDictValue("order_area", area))) {
                                errortext += "序号为第" + info.getIdx() + "行数据，地区不存在或不能为空！";
                            } else {
                                // 地区字典翻译
                                entity.setArea(DictUtils.getDictValue("order_area", area));
                            }

                            Calendar calendar = Calendar.getInstance();
                            entity.setYear(String.valueOf(calendar.get(Calendar.YEAR)));

                            if (StringUtils.isNotBlank(errortext)) {
                                map.put("errorText", errortext);
                                map.put("orderInsertCount", orderInsertCount);
                                map.put("orderUpdateCount", orderUpdateCount);
                                return map;

                            } else {
                                list1.add(entity);
                            }
                        }
                    } else {
                        errortext += "序号为" + info.getIdx() + "行数据，序号不能为空，请填写后导入！";
                    }
                }
            }
            if (StringUtils.isBlank(errortext)) {
                for (ProjectBaseInfo info : list1) {
                    ProjectBaseInfo projectBaseInfo = new ProjectBaseInfo();
                    projectBaseInfo.setCode(info.getCode());
                    List<ProjectBaseInfo> orderList = projectBaseInfoMapper.selectList(projectBaseInfo);
                    if (orderList.size() > 0) {
                        info.setId(orderList.get(0).getId());
                        orderUpdateCount += this.update(info);
                    } else {
                        orderInsertCount += this.insert(info);
                    }
                }

                for (ProjectBaseInfo info : list1) {
                    String goodsCode = dealParamData(info.getParams(), "goodsCode");
                    String contractGoodsName = dealParamData(info.getParams(), "contractGoodsName");
                    String goodsCounts = dealParamData(info.getParams(), "goodsCounts");
                    String goodsUnitPrice = dealParamData(info.getParams(), "goodsUnitPrice");
                    String goodsTotalPrice = dealParamData(info.getParams(), "goodsTotalPrice");
                    String goodsTaxUnitPrice = dealParamData(info.getParams(), "goodsTaxUnitPrice");
                    String goodsTaxTotalPrice = dealParamData(info.getParams(), "goodsTaxTotalPrice");
                    String gongchengName = dealParamData(info.getParams(), "gongchengName");
                    String deliveryPerson = dealParamData(info.getParams(), "deliveryPerson");
                    String deliveryTime = dealParamData(info.getParams(), "deliveryTime");
                    String remark = dealParamData(info.getParams(), "information");
                    String projectDept = dealParamData(info.getParams(), "projectDept");

                    if (info.getContractMoney() == null) {
                        info.setContractMoney(new BigDecimal(0));
                    }
                    ProjectBaseInfo projectBaseInfo = projectBaseInfoMapper.selectById(info.getId());
                    projectBaseInfo.setContractMoney(projectBaseInfo.getContractMoney().add(new BigDecimal(goodsTaxTotalPrice)));
                    projectBaseInfo.setActualMoney(projectBaseInfo.getActualMoney().add(new BigDecimal(goodsTaxTotalPrice)));
                    projectBaseInfo.setTaxRemain(projectBaseInfo.getContractMoney());
                    projectBaseInfo.setCompanyName(projectDept);
                    projectBaseInfoMapper.update(projectBaseInfo);

                    GoodsSale goodsSale = new GoodsSale();
                    goodsSale.setGongchengName(gongchengName);
                    goodsSale.setProjectId(info.getId());
                    goodsSale.setGoodsCode(goodsCode);
                    goodsSale.setGoodsId(info.getGoods().getId());
                    goodsSale.setGoodsType(info.getGoods().getType());
                    goodsSale.setGoodsName(info.getGoods().getName());
                    goodsSale.setContractGoodsName(contractGoodsName);
                    goodsSale.setDeliveryTime(DateUtils.getDateFromExcel(deliveryTime));
                    goodsSale.setGoodsBrand(info.getGoods().getBrand());
                    goodsSale.setGoodModel(info.getGoods().getModel());
                    goodsSale.setProjectNo(info.getCode());
                    goodsSale.setProjectName(info.getName());
                    goodsSale.setSort(Integer.parseInt(info.getIdx()));
                    goodsSale.setId(IdUtils.fastSimpleUUID());
                    goodsSale.setCreateTime(DateUtils.getNowDate());
                    goodsSale.setCreateBy(SecurityUtils.getUsername());
                    goodsSale.setOrderCount(new BigDecimal(goodsCounts));
                    goodsSale.setFahuoShengyu(new BigDecimal(goodsCounts));
                    goodsSale.setGoodsUnitPrice(new BigDecimal(goodsUnitPrice));
                    goodsSale.setGoodsTotalPrice(new BigDecimal(goodsTotalPrice));
                    goodsSale.setGoodsTaxUnitPrice(new BigDecimal(goodsTaxUnitPrice));
                    goodsSale.setGoodsTaxTotalPrice(new BigDecimal(goodsTaxTotalPrice));
                    goodsSale.setDeliveryPerson(deliveryPerson);
                    goodsSale.setRemark(remark);
                    goodsSale.setProjectDept(projectDept);
                    goodsSaleMapper.insert(goodsSale);
                    goodsInsertCount++;

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("errorText", errortext);
        map.put("orderInsertCount", orderInsertCount);
        map.put("orderUpdateCount", orderUpdateCount);
        map.put("goodsInsertCount", goodsInsertCount);
        map.put("goodsUpdateCount", goodsUpdateCount);
        return map;
    }


    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Map<String, Object> imporGoodsChuan(ProjectBaseInfo contact, MultipartFile file) {
        String tmplName = "projectBaseInfoAndGoodsChuan.xml";
        String errortext = "";
        Map<String, Object> map = new HashMap<>();
        int i = 0;
        int j = 0;
        try {
            InputStream in = new FileInputStream(basePath + File.separator
                    + templatePath + File.separator + templateImport + File.separator + tmplName);
            XLSReader mainReader = ReaderBuilder.buildFromXML(in);
            List<GoodsSaleChuan> list = new ArrayList<>();
            List<GoodsSaleChuan> listToDo = new ArrayList<>();
            Map beans = new HashMap();
            beans.put("list", list);
            XLSReadStatus readStatus = mainReader.read(file.getInputStream(), beans);
            if (readStatus.isStatusOK()) {
                for (int k = 0; k < list.size(); k++) {
                    GoodsSaleChuan entity = new GoodsSaleChuan();
                    entity.setId(IdUtils.fastSimpleUUID());
                    GoodsSaleChuan info = list.get(k);
                    BeanUtils.copyProperties(info, entity, "id");

                    if (StringUtils.isBlank(info.getProjectCode())) {
                        errortext += "序号为" + info.getIdx() + "行数据，订单编号不能为空，请填写后导入！";
                    } else {
                        String projectNo = info.getProjectCode().replace("\n", "").replace("\r", "");
                        ProjectBaseInfo projectBaseInfo = this.selectByCode(projectNo);
                        if (projectBaseInfo == null) {
                            errortext += "序号为" + info.getIdx() + "行数据，订单编号不存在，请先录入订单！";
                            break;
                        } else {
                            entity.setProjectId(projectBaseInfo.getId());
                            entity.setProjectCode(projectNo);
                            entity.setCustomerId(projectBaseInfo.getCustomId());
                            entity.setCustomerName(projectBaseInfo.getCustomName());
                            entity.setGongchengName(projectBaseInfo.getGongchengName());
                            entity.setDeliveryTime(projectBaseInfo.getDeliveryTime());
                            if (StringUtils.isBlank(info.getGoodsModel())) {
                                errortext += "序号为" + info.getIdx() + "行数据，合同产品型号不能为空，请填写后导入！";
                                break;
                            } else {
                                List<GoodsSale> goodsSaleList =goodsSaleMapper.selectByModelAndProject(projectBaseInfo.getId(),info.getGoodsModel());
                                if(goodsSaleList.size()>0){
                                    entity.setGoodsCode(goodsSaleList.get(0).getGoodsCode());
                                    entity.setGoodsName(goodsSaleList.get(0).getGoodsName());
                                    entity.setGoodsModel(goodsSaleList.get(0).getGoodModel());
                                    entity.setGoodsSaleId(goodsSaleList.get(0).getId());
                                    entity.setGoodsId(goodsSaleList.get(0).getGoodsId());
                                    entity.setGongchengName(goodsSaleList.get(0).getGongchengName());
                                    entity.setSaleDate(goodsSaleList.get(0).getSaleDate());
                                }else{
                                    errortext += "序号为" + info.getIdx() + "行数据，关联销售订单单行金具型号不存在，请填写后导入！";
                                    break;
                                }
                            }

                        }
                    }
                    if (StringUtils.isNotBlank(info.getGongchengName())) {
                        entity.setGongchengName(info.getGongchengName());
                    }


                    if (StringUtils.isBlank(info.getName())) {
                        errortext += "序号为" + info.getIdx() + "行数据，合同产品名称不能为空，请填写后导入！";
                        break;
                    } else {
                        entity.setName(info.getName());
                    }

                    if (StringUtils.isBlank(info.getModels())) {
                        errortext += "序号为" + info.getIdx() + "行数据，合同产品型号不能为空，请填写后导入！";
                        break;
                    } else {
                        entity.setModels(info.getModels());
                    }

                    try {
                        if(StringUtils.isNotBlank(info.getCountStr())){
                            entity.setCount(new BigDecimal(info.getCountStr()));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errortext += "行号为 " + info.getIdx() + "行的数据，含税单价格式错误，请修改后再上传！";
                        break;
                    }
                    try {
                        if(StringUtils.isNotBlank(info.getWeightStr())) {
                            entity.setWeight(new BigDecimal(info.getWeightStr()));
                        }
                    } catch (Exception e) {
                        errortext += "行号为 " + info.getIdx() + "行的数据，含税价格格式错误，请修改后再上传！";
                        break;
                    }
                    try {
                        if(StringUtils.isNotBlank(info.getGoodsCountStr())){
                            entity.setGoodsCount(new BigDecimal(info.getGoodsCountStr()));
                        }
                    } catch (Exception e) {
                        errortext += "行号为 " + info.getIdx() + "行的数据，含税价格格式错误，请修改后再上传！";
                        break;
                    }
                    if (StringUtils.isNotBlank(info.getRemark())) {
                        entity.setRemark(info.getRemark());
                    }

                    entity.setType("2");
                    if (StringUtils.isNotBlank(errortext)) {
                        map.put("errorText", errortext);
                        map.put("num", i);
                        map.put("numupdate", j);
                        return map;
                    } else {
                        listToDo.add(entity);
                    }
                }
            }
            if (StringUtils.isBlank(errortext)) {
                for (GoodsSaleChuan info : listToDo) {
                    i += goodsSaleChuanService.insert(info);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("errorText", errortext);
        map.put("num", i);
        map.put("numupdate", j);
        return map;
    }

    private String dealParamData(Map<String, Object> params, String name) {
        String result = params.get(name) != null ? params.get(name).toString() : "";
        result = result.replace("\n", "").replace("\r", ""); //去掉回车和换行
        return result;
    }


    /**
     * 导入铁构件订单信息
     */
    @Override
    public Map<String, Object> importIronOrderData(ProjectBaseInfo order, MultipartFile file) {
        String tmplName = "projectBaseInfoIron.xml";
        String errortext = "";
        Map<String, Object> map = new HashMap<>();
        int orderInsertCount = 0;
        int orderUpdateCount = 0;
        map.put("orderInsertCount", orderInsertCount);
        map.put("orderUpdateCount", orderUpdateCount);
        try {
            InputStream in = new FileInputStream(basePath + File.separator
                    + templatePath + File.separator + templateImport + File.separator + tmplName);
            XLSReader mainReader = ReaderBuilder.buildFromXML(in);
            List<ProjectBaseInfo> list = new ArrayList<>();
            List<ProjectBaseInfo> list1 = new ArrayList<>();

            Map beans = new HashMap();
            beans.put("list", list);
            XLSReadStatus readStatus = mainReader.read(file.getInputStream(), beans);
            if (readStatus.isStatusOK()) {
                for (ProjectBaseInfo info : list) {
                    ProjectBaseInfo entity = new ProjectBaseInfo();
                    entity.setId(IdUtils.fastSimpleUUID());
                    BeanUtils.copyProperties(info, entity, "id");
                    if (StringUtils.isNotBlank(info.getIdx())) {
                        if (StringUtils.isNotBlank(info.getCode())) {
                            String code = info.getParams().get("code") != null ? info.getParams().get("code").toString().trim() : "";
                            if (StringUtils.isBlank(code)) {
                                errortext += "序号为" + info.getIdx() + "行数据，框架编号不能为空，请填写后导入！";
                            } else {
                                Project project = projectService.selectProjectByCode(code);
                                if (project == null) {
                                    errortext += "序号为" + info.getIdx() + "行数据，框架编号不存在，请填写后导入！";
                                } else {
                                    entity.setProject(project);
                                    entity.setProjectId(project.getId());
                                }
                            }

                            if (StringUtils.isBlank(info.getCode())) {
                                errortext += "序号为" + info.getIdx() + "行数据，订单编号不能为空，请填写后导入！";
                            } else {
                                ProjectBaseInfo projectBaseInfo = projectBaseInfoMapper.selectByCode(info.getCode());
                                if (projectBaseInfo != null) {
                                    errortext += "序号为" + info.getIdx() + "行数据，订单在系统中已经存在，请检查后导入！";
                                } else {

                                }
                            }

                            if (StringUtils.isBlank(info.getCreateName())) {
                                errortext += "序号为" + info.getIdx() + "行数据，制单人不能为空，请填写后导入！";
                            } else {
                                SysUser sysUser = iSysUserService.selectUserByUserName(info.getCreateName().trim());
                                if (sysUser != null) {
                                    entity.setCreateName(sysUser.getNickName());
                                } else {
                                    errortext += "序号为" + info.getIdx() + "行数据，制单人不存在，请检查后导入！";
                                }
                            }

                            if (StringUtils.isBlank(info.getSalesmanName())) {
                                errortext += "序号为" + info.getIdx() + "行数据，订单业务员不能为空，请填写后导入！";
                            } else {
                                SysUser sysUser = iSysUserService.selectUserByUserName(info.getSalesmanName().trim());
                                if (sysUser != null) {
                                    entity.setSalesmanId(sysUser.getUserId());
                                    entity.setDeptId(sysUser.getDeptId());
                                    entity.setDeptName(sysUser.getDept().getDeptName());
                                } else {
                                    errortext += "序号为" + info.getIdx() + "行数据，订单业务员不存在，请检查后导入！";
                                }
                            }
                            if (StringUtils.isBlank(info.getCustomerCode())) {
                                errortext += "序号为" + info.getIdx() + "行数据，买方编码不能为空，请填写后导入！";
                            } else {
                                GoodsCustomer goodsCustomer = iGoodsCustomerService.selectByCode(info.getCustomerCode());
                                if (goodsCustomer != null) {
                                    entity.setCustomId(goodsCustomer.getId());
                                    entity.setCustomName(goodsCustomer.getName());
                                    entity.setTaxcode(goodsCustomer.getTaxNo());
                                } else {
                                    errortext += "序号为" + info.getIdx() + "行数据，买方编码不存在，请检查后导入！";
                                }
                            }

                            String contractDate = info.getParams().get("contractDate") != null ? info.getParams().get("contractDate").toString() : "";
                            if (StringUtils.isNotBlank(contractDate)) {
                                try {
                                    Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");
                                    Matcher isNum = pattern.matcher(contractDate);
                                    if (!isNum.matches()) {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        entity.setContractDate(df.parse(contractDate));
                                    } else {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        String date = df.format(DateUtil.getJavaDate(Double.parseDouble(contractDate)));
                                        entity.setContractDate(DateUtils.parseDate(date, "yyyy-MM-dd"));
                                    }
                                } catch (Exception e) {
                                    errortext += "序号为第" + info.getIdx() + "行数据，订单签订时间格式错误，请规定的日期格式进行修改！";
                                    e.printStackTrace();
                                }
                            }

                            String deliveryTime = info.getParams().get("deliveryTime") != null ? info.getParams().get("deliveryTime").toString() : "";
                            if (StringUtils.isNotBlank(deliveryTime)) {
                                try {
                                    Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");
                                    Matcher isNum = pattern.matcher(deliveryTime);
                                    if (!isNum.matches()) {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        entity.setDeliveryTime(df.parse(deliveryTime));
                                    } else {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        String date = df.format(DateUtil.getJavaDate(Double.parseDouble(deliveryTime)));
                                        entity.setDeliveryTime(DateUtils.parseDate(date, "yyyy-MM-dd"));
                                    }
                                } catch (Exception e) {
                                    errortext += "序号为第" + info.getIdx() + "行数据，合同交货时间格式错误，请规定的日期格式进行修改！";
                                    e.printStackTrace();
                                }
                            }

                            String orderDate = info.getParams().get("orderDate") != null ? info.getParams().get("orderDate").toString() : "";
                            if (StringUtils.isNotBlank(orderDate)) {
                                try {
                                    Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");
                                    Matcher isNum = pattern.matcher(orderDate);
                                    if (!isNum.matches()) {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        entity.setOrderDate(df.parse(orderDate));
                                    } else {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        String date = df.format(DateUtil.getJavaDate(Double.parseDouble(orderDate)));
                                        entity.setOrderDate(DateUtils.parseDate(date, "yyyy-MM-dd"));
                                    }
                                } catch (Exception e) {
                                    errortext += "序号为第" + info.getIdx() + "行数据，下单日期格式错误，请规定的日期格式进行修改！";
                                    e.printStackTrace();
                                }
                            }

//                            String gongchengName = info.getParams().get("gongchengName") != null ? info.getParams().get("gongchengName").toString() : "";
//                            if(StringUtils.isBlank(gongchengName)){
//                                errortext += "序号为第" + info.getIdx() + "行数据，工程名称不能为空！";
//                            }

                            String weight = info.getParams().get("weight") != null ? info.getParams().get("weight").toString() : "";
                            if (StringUtils.isBlank(weight)) {
                                errortext += "序号为第" + info.getIdx() + "行数据，重量不能为空！";
                            } else {
                                entity.setWeight(new BigDecimal(weight));
                            }

                            String ironUnitPrice = info.getParams().get("ironUnitPrice") != null ? info.getParams().get("ironUnitPrice").toString() : "";
                            if (StringUtils.isBlank(ironUnitPrice)) {
                                errortext += "序号为第" + info.getIdx() + "行数据，铁件单价不能为空！";
                            } else {
                                entity.setIronUnitPrice(new BigDecimal(ironUnitPrice));
                            }
                            String ironTaxUnitPrice = info.getParams().get("ironTaxUnitPrice") != null ? info.getParams().get("ironTaxUnitPrice").toString() : "";
                            if (StringUtils.isBlank(ironTaxUnitPrice)) {
                                errortext += "序号为第" + info.getIdx() + "行数据，铁件含税单价不能为空！";
                            } else {
                                entity.setIronTaxUnitPrice(new BigDecimal(ironTaxUnitPrice));
                            }

                            String ironTotalPrice = info.getParams().get("ironTotalPrice") != null ? info.getParams().get("ironTotalPrice").toString() : "";

                            if (StringUtils.isBlank(ironTotalPrice)) {
                                errortext += "序号为第" + info.getIdx() + "行数据，铁件含税单价不能为空！";
                            } else {
                                entity.setIronTotalPrice(new BigDecimal(ironTotalPrice));
                            }
                            String ironTaxTotalPrice = info.getParams().get("ironTaxTotalPrice") != null ? info.getParams().get("ironTaxTotalPrice").toString() : "";
                            if (StringUtils.isBlank(ironTaxTotalPrice)) {
                                errortext += "序号为第" + info.getIdx() + "行数据，铁件含税总价不能为空！";
                            } else {
                                entity.setIronTaxTotalPrice(new BigDecimal(ironTaxTotalPrice));
                                entity.setContractMoney(new BigDecimal(ironTaxTotalPrice));
                            }

                            String area = info.getArea();
                            if (StringUtils.isBlank(area) || StringUtils.isBlank(DictUtils.getDictValue("order_area", area))) {
                                errortext += "序号为第" + info.getIdx() + "行数据，地区不存在或不能为空！";
                            } else {
                                // 地区字典翻译
                                entity.setArea(DictUtils.getDictValue("order_area", area));
                            }

                            Calendar calendar = Calendar.getInstance();
                            entity.setYear(String.valueOf(calendar.get(Calendar.YEAR)));
                            if (StringUtils.isNotBlank(errortext)) {
                                map.put("errorText", errortext);
                                map.put("orderInsertCount", orderInsertCount);
                                map.put("orderUpdateCount", orderUpdateCount);
                                return map;
                            } else {
                                list1.add(entity);
                            }
                        }
                    } else {
                        errortext += "序号为" + info.getIdx() + "行数据，订单编号不能为空，请填写后导入！";
                    }
                }
            }
            if (StringUtils.isBlank(errortext)) {
                for (ProjectBaseInfo info : list1) {
                    info.setGoodsType(BusinessConstants.ORDER_GOODS_TYPE_IRON);
                    ProjectBaseInfo projectBaseInfo = new ProjectBaseInfo();
                    projectBaseInfo.setCode(info.getCode());
                    List<ProjectBaseInfo> orderList = projectBaseInfoMapper.selectList(projectBaseInfo);
                    if (orderList.size() > 0) {
                        info.setId(orderList.get(0).getId());
                        orderUpdateCount += this.update(info);
                    } else {
                        orderInsertCount += this.insert(info);
                    }
                }
                for (ProjectBaseInfo info : list1) {
                    if (info.getContractMoney() == null) {
                        info.setContractMoney(new BigDecimal(0));
                    }
                    ProjectBaseInfo projectBaseInfo = projectBaseInfoMapper.selectById(info.getId());
                    projectBaseInfo.setTaxRemain(projectBaseInfo.getContractMoney());
                    projectBaseInfoMapper.update(projectBaseInfo);

                    //
                    OrderIronRecord orderIronRecord = new OrderIronRecord();
                    orderIronRecord.setOrderId(info.getId());
                    orderIronRecord.setDeliveryDate(info.getDeliveryTime());
                    orderIronRecord.setOrderCode(info.getCode());
                    orderIronRecord.setContacts(info.getDeliveryPerson());
                    orderIronRecord.setPhone(info.getDeliveryPersonTel());
                    orderIronRecord.setWeight(info.getWeight());
                    orderIronRecordService.insert(orderIronRecord);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("errorText", errortext);
        map.put("orderInsertCount", orderInsertCount);
        map.put("orderUpdateCount", orderUpdateCount);
        return map;
    }


    /**
     * 导入金具订单（不含产品）
     */
    @Override
    public Map<String, Object> importOrderNoGoods(ProjectBaseInfo order, MultipartFile file) {
        String tmplName = "projectBaseInfoNoGoods.xml";
        String errortext = "";
        Map<String, Object> map = new HashMap<>();
        int orderInsertCount = 0;
        int orderUpdateCount = 0;
        map.put("orderInsertCount", orderInsertCount);
        map.put("orderUpdateCount", orderUpdateCount);
        try {
            InputStream in = new FileInputStream(basePath + File.separator
                    + templatePath + File.separator + templateImport + File.separator + tmplName);
            XLSReader mainReader = ReaderBuilder.buildFromXML(in);
            List<ProjectBaseInfo> list = new ArrayList<>();
            List<ProjectBaseInfo> list1 = new ArrayList<>();

            Map beans = new HashMap();
            beans.put("list", list);
            XLSReadStatus readStatus = mainReader.read(file.getInputStream(), beans);
            if (readStatus.isStatusOK()) {
                for (ProjectBaseInfo info : list) {
                    ProjectBaseInfo entity = new ProjectBaseInfo();
                    entity.setId(IdUtils.fastSimpleUUID());
                    BeanUtils.copyProperties(info, entity, "id");
                    if (StringUtils.isNotBlank(info.getIdx())) {
                        if (StringUtils.isNotBlank(info.getCode())) {
                            String code = info.getParams().get("code") != null ? info.getParams().get("code").toString().trim() : "";
                            if (StringUtils.isBlank(code)) {
                                errortext += "序号为" + info.getIdx() + "行数据，框架编号不能为空，请填写后导入！";
                            } else {
                                Project project = projectService.selectProjectByCode(code);
                                if (project == null) {
                                    errortext += "序号为" + info.getIdx() + "行数据，框架编号不存在，请填写后导入！";
                                } else {
                                    entity.setProject(project);
                                    entity.setProjectId(project.getId());
                                }
                            }

                            if (StringUtils.isBlank(info.getCode())) {
                                errortext += "序号为" + info.getIdx() + "行数据，订单编号不能为空，请填写后导入！";
                            } else {
                                ProjectBaseInfo projectBaseInfo = projectBaseInfoMapper.selectByCode(info.getCode());
                                if (projectBaseInfo != null) {
                                    errortext += "序号为" + info.getIdx() + "行数据，订单在系统中已经存在，请检查后导入！";
                                } else {

                                }
                            }

                            if (StringUtils.isBlank(info.getCreateName())) {
                                errortext += "序号为" + info.getIdx() + "行数据，制单人不能为空，请填写后导入！";
                            } else {
                                SysUser sysUser = iSysUserService.selectUserByUserName(info.getCreateName().trim());
                                if (sysUser != null) {
                                    entity.setCreateName(sysUser.getNickName());
                                } else {
                                    errortext += "序号为" + info.getIdx() + "行数据，制单人不存在，请检查后导入！";
                                }
                            }

                            if (StringUtils.isBlank(info.getSalesmanName())) {
                                errortext += "序号为" + info.getIdx() + "行数据，订单业务员不能为空，请填写后导入！";
                            } else {
                                SysUser sysUser = iSysUserService.selectUserByUserName(info.getSalesmanName().trim());
                                if (sysUser != null) {
                                    entity.setSalesmanId(sysUser.getUserId());
                                    entity.setDeptId(sysUser.getDeptId());
                                    entity.setDeptName(sysUser.getDept().getDeptName());
                                } else {
                                    errortext += "序号为" + info.getIdx() + "行数据，订单业务员不存在，请检查后导入！";
                                }
                            }
                            if (StringUtils.isBlank(info.getCustomerCode())) {
                                errortext += "序号为" + info.getIdx() + "行数据，买方编码不能为空，请填写后导入！";
                            } else {
                                GoodsCustomer goodsCustomer = iGoodsCustomerService.selectByCode(info.getCustomerCode());
                                if (goodsCustomer != null) {
                                    entity.setCustomId(goodsCustomer.getId());
                                    entity.setCustomName(goodsCustomer.getName());
                                    entity.setTaxcode(goodsCustomer.getTaxNo());
                                } else {
                                    errortext += "序号为" + info.getIdx() + "行数据，买方编码不存在，请检查后导入！";
                                }
                            }

                            String contractDate = info.getParams().get("contractDate") != null ? info.getParams().get("contractDate").toString() : "";
                            if (StringUtils.isNotBlank(contractDate)) {
                                try {
                                    Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");
                                    Matcher isNum = pattern.matcher(contractDate);
                                    if (!isNum.matches()) {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        entity.setContractDate(df.parse(contractDate));
                                    } else {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        String date = df.format(DateUtil.getJavaDate(Double.parseDouble(contractDate)));
                                        entity.setContractDate(DateUtils.parseDate(date, "yyyy-MM-dd"));
                                    }
                                } catch (Exception e) {
                                    errortext += "序号为第" + info.getIdx() + "行数据，订单签订时间格式错误，请规定的日期格式进行修改！";
                                    e.printStackTrace();
                                }
                            }

                            String deliveryTime = info.getParams().get("deliveryTime") != null ? info.getParams().get("deliveryTime").toString() : "";
                            if (StringUtils.isNotBlank(deliveryTime)) {
                                try {
                                    Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");
                                    Matcher isNum = pattern.matcher(deliveryTime);
                                    if (!isNum.matches()) {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        entity.setDeliveryTime(df.parse(deliveryTime));
                                    } else {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        String date = df.format(DateUtil.getJavaDate(Double.parseDouble(deliveryTime)));
                                        entity.setDeliveryTime(DateUtils.parseDate(date, "yyyy-MM-dd"));
                                    }
                                } catch (Exception e) {
                                    errortext += "序号为第" + info.getIdx() + "行数据，合同交货时间格式错误，请规定的日期格式进行修改！";
                                    e.printStackTrace();
                                }
                            }

                            String orderDate = info.getParams().get("orderDate") != null ? info.getParams().get("orderDate").toString() : "";
                            if (StringUtils.isNotBlank(orderDate)) {
                                try {
                                    Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");
                                    Matcher isNum = pattern.matcher(orderDate);
                                    if (!isNum.matches()) {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        entity.setOrderDate(df.parse(orderDate));
                                    } else {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        String date = df.format(DateUtil.getJavaDate(Double.parseDouble(orderDate)));
                                        entity.setOrderDate(DateUtils.parseDate(date, "yyyy-MM-dd"));
                                    }
                                } catch (Exception e) {
                                    errortext += "序号为第" + info.getIdx() + "行数据，下单日期格式错误，请规定的日期格式进行修改！";
                                    e.printStackTrace();
                                }
                            }

                            String contractMoney = info.getParams().get("contractMoney") != null ? info.getParams().get("contractMoney").toString() : "";
                            if (StringUtils.isBlank(contractMoney)) {
                                errortext += "序号为第" + info.getIdx() + "行数据，合同金额不能为空！";
                            } else {
                                entity.setContractMoney(new BigDecimal(contractMoney));
                            }

                            String area = info.getArea();
                            if (StringUtils.isBlank(area) || StringUtils.isBlank(DictUtils.getDictValue("order_area", area))) {
                                errortext += "序号为第" + info.getIdx() + "行数据，地区不存在或不能为空！";
                            } else {
                                // 地区字典翻译
                                entity.setArea(DictUtils.getDictValue("order_area", area));
                            }

                            if (StringUtils.isBlank(info.getGoodsType())) {
                                errortext += "序号为" + info.getIdx() + "行数据，订单产品类别不能为空，请填写后导入！";
                            } else {
                                entity.setGoodsType(DictUtils.getDictValue("order_goods_type", info.getGoodsType()));
                            }

                            Calendar calendar = Calendar.getInstance();
                            entity.setYear(String.valueOf(calendar.get(Calendar.YEAR)));
                            if (StringUtils.isNotBlank(errortext)) {
                                map.put("errorText", errortext);
                                map.put("orderInsertCount", orderInsertCount);
                                map.put("orderUpdateCount", orderUpdateCount);
                                return map;
                            } else {
                                list1.add(entity);
                            }
                        }
                    } else {
                        errortext += "序号为" + info.getIdx() + "行数据，订单编号不能为空，请填写后导入！";
                    }
                }
            }
            if (StringUtils.isBlank(errortext)) {
                for (ProjectBaseInfo info : list1) {
                    info.setGoodsType(BusinessConstants.ORDER_GOODS_TYPE_HARDWARE);
                    ProjectBaseInfo projectBaseInfo = new ProjectBaseInfo();
                    projectBaseInfo.setCode(info.getCode());
                    List<ProjectBaseInfo> orderList = projectBaseInfoMapper.selectList(projectBaseInfo);
                    if (orderList.size() > 0) {
                        info.setId(orderList.get(0).getId());
                        orderUpdateCount += this.update(info);
                    } else {
                        orderInsertCount += this.insert(info);
                    }
                }
                for (ProjectBaseInfo info : list1) {
                    if (info.getContractMoney() == null) {
                        info.setContractMoney(new BigDecimal(0));
                    }
                    ProjectBaseInfo projectBaseInfo = projectBaseInfoMapper.selectById(info.getId());
                    projectBaseInfo.setTaxRemain(projectBaseInfo.getContractMoney());
                    projectBaseInfoMapper.update(projectBaseInfo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("errorText", errortext);
        map.put("orderInsertCount", orderInsertCount);
        map.put("orderUpdateCount", orderUpdateCount);
        return map;
    }

    /**
     * 导入铁构件订单信息（带明细）
     */
    @Override
    public Map<String, Object> importOrderForIronDetail(ProjectBaseInfo order, MultipartFile file) {
        String tmplName = "projectBaseInfoIronDetail.xml";
        String errortext = "";
        Map<String, Object> map = new HashMap<>();
        int orderInsertCount = 0;
        int orderUpdateCount = 0;
        int ironDetailInsertCount = 0;
        map.put("orderInsertCount", orderInsertCount);
        map.put("orderUpdateCount", orderUpdateCount);
        try {
            InputStream in = new FileInputStream(basePath + File.separator
                    + templatePath + File.separator + templateImport + File.separator + tmplName);
            XLSReader mainReader = ReaderBuilder.buildFromXML(in);
            List<ProjectBaseInfo> list = new ArrayList<>();
            List<ProjectBaseInfo> list1 = new ArrayList<>();

            Map beans = new HashMap();
            beans.put("list", list);
            XLSReadStatus readStatus = mainReader.read(file.getInputStream(), beans);
            if (readStatus.isStatusOK()) {
                for (ProjectBaseInfo info : list) {
                    ProjectBaseInfo entity = new ProjectBaseInfo();
                    entity.setId(IdUtils.fastSimpleUUID());
                    BeanUtils.copyProperties(info, entity, "id");
                    if (StringUtils.isNotBlank(info.getIdx())) {
                        if (StringUtils.isNotBlank(info.getCode())) {
                            String code = info.getParams().get("code") != null ? info.getParams().get("code").toString().trim() : "";
                            if (StringUtils.isBlank(code)) {
                                errortext += "序号为" + info.getIdx() + "行数据，框架编号不能为空，请填写后导入！";
                            } else {
                                Project project = projectService.selectProjectByCode(code);
                                if (project == null) {
                                    errortext += "序号为" + info.getIdx() + "行数据，框架编号不存在，请填写后导入！";
                                } else {
                                    entity.setProject(project);
                                    entity.setProjectId(project.getId());
                                }
                            }

                            if (StringUtils.isBlank(info.getCode())) {
                                errortext += "序号为" + info.getIdx() + "行数据，订单编号不能为空，请填写后导入！";
                            } else {
                                ProjectBaseInfo projectBaseInfo = projectBaseInfoMapper.selectByCode(info.getCode());
                                if (projectBaseInfo != null) {
                                    errortext += "序号为" + info.getIdx() + "行数据，订单在系统中已经存在，请检查后导入！";
                                } else {

                                }
                            }

                            if (StringUtils.isBlank(info.getCreateName())) {
                                errortext += "序号为" + info.getIdx() + "行数据，制单人不能为空，请填写后导入！";
                            } else {
                                SysUser sysUser = iSysUserService.selectUserByUserName(info.getCreateName().trim());
                                if (sysUser != null) {
                                    entity.setCreateName(sysUser.getNickName());
                                } else {
                                    errortext += "序号为" + info.getIdx() + "行数据，制单人不存在，请检查后导入！";
                                }
                            }

                            if (StringUtils.isBlank(info.getSalesmanName())) {
                                errortext += "序号为" + info.getIdx() + "行数据，订单业务员不能为空，请填写后导入！";
                            } else {
                                SysUser sysUser = iSysUserService.selectUserByUserName(info.getSalesmanName().trim());
                                if (sysUser != null) {
                                    entity.setSalesmanId(sysUser.getUserId());
                                    entity.setDeptId(sysUser.getDeptId());
                                    entity.setDeptName(sysUser.getDept().getDeptName());
                                } else {
                                    errortext += "序号为" + info.getIdx() + "行数据，订单业务员不存在，请检查后导入！";
                                }
                            }
                            if (StringUtils.isBlank(info.getCustomerCode())) {
                                errortext += "序号为" + info.getIdx() + "行数据，买方编码不能为空，请填写后导入！";
                            } else {
                                GoodsCustomer goodsCustomer = iGoodsCustomerService.selectByCode(info.getCustomerCode());
                                if (goodsCustomer != null) {
                                    entity.setCustomId(goodsCustomer.getId());
                                    entity.setCustomName(goodsCustomer.getName());
                                    entity.setTaxcode(goodsCustomer.getTaxNo());
                                } else {
                                    errortext += "序号为" + info.getIdx() + "行数据，买方编码不存在，请检查后导入！";
                                }
                            }

                            String contractDate = info.getParams().get("contractDate") != null ? info.getParams().get("contractDate").toString() : "";
                            if (StringUtils.isNotBlank(contractDate)) {
                                try {
                                    Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");
                                    Matcher isNum = pattern.matcher(contractDate);
                                    if (!isNum.matches()) {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        entity.setContractDate(df.parse(contractDate));
                                    } else {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        String date = df.format(DateUtil.getJavaDate(Double.parseDouble(contractDate)));
                                        entity.setContractDate(DateUtils.parseDate(date, "yyyy-MM-dd"));
                                    }
                                } catch (Exception e) {
                                    errortext += "序号为第" + info.getIdx() + "行数据，订单签订时间格式错误，请规定的日期格式进行修改！";
                                    e.printStackTrace();
                                }
                            }

                            String deliveryTime = info.getParams().get("deliveryTime") != null ? info.getParams().get("deliveryTime").toString() : "";
                            if (StringUtils.isNotBlank(deliveryTime)) {
                                try {
                                    Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");
                                    Matcher isNum = pattern.matcher(deliveryTime);
                                    if (!isNum.matches()) {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        entity.setDeliveryTime(df.parse(deliveryTime));
                                    } else {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        String date = df.format(DateUtil.getJavaDate(Double.parseDouble(deliveryTime)));
                                        entity.setDeliveryTime(DateUtils.parseDate(date, "yyyy-MM-dd"));
                                    }
                                } catch (Exception e) {
                                    errortext += "序号为第" + info.getIdx() + "行数据，合同交货时间格式错误，请规定的日期格式进行修改！";
                                    e.printStackTrace();
                                }
                            }

                            String orderDate = info.getParams().get("orderDate") != null ? info.getParams().get("orderDate").toString() : "";
                            if (StringUtils.isNotBlank(orderDate)) {
                                try {
                                    Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");
                                    Matcher isNum = pattern.matcher(orderDate);
                                    if (!isNum.matches()) {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        entity.setOrderDate(df.parse(orderDate));
                                    } else {
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                        String date = df.format(DateUtil.getJavaDate(Double.parseDouble(orderDate)));
                                        entity.setOrderDate(DateUtils.parseDate(date, "yyyy-MM-dd"));
                                    }
                                } catch (Exception e) {
                                    errortext += "序号为第" + info.getIdx() + "行数据，下单日期格式错误，请规定的日期格式进行修改！";
                                    e.printStackTrace();
                                }
                            }

//                            String weight = info.getParams().get("weight") != null ? info.getParams().get("weight").toString() : "";
//                            if(StringUtils.isBlank(weight)){
//                                errortext += "序号为第" + info.getIdx() + "行数据，重量不能为空！";
//                            }else{
//                                entity.setWeight(new BigDecimal(weight));
//                            }

                            String ironUnitPrice = info.getParams().get("ironUnitPrice") != null ? info.getParams().get("ironUnitPrice").toString() : "";
                            if (StringUtils.isBlank(ironUnitPrice)) {
                                errortext += "序号为第" + info.getIdx() + "行数据，铁件单价不能为空！";
                            } else {
                                entity.setIronUnitPrice(new BigDecimal(ironUnitPrice));
                            }
                            String ironTaxUnitPrice = info.getParams().get("ironTaxUnitPrice") != null ? info.getParams().get("ironTaxUnitPrice").toString() : "";
                            if (StringUtils.isBlank(ironTaxUnitPrice)) {
                                errortext += "序号为第" + info.getIdx() + "行数据，铁件含税单价不能为空！";
                            } else {
                                entity.setIronTaxUnitPrice(new BigDecimal(ironTaxUnitPrice));
                            }

                            String ironTotalPrice = info.getParams().get("ironTotalPrice") != null ? info.getParams().get("ironTotalPrice").toString() : "";

                            if (StringUtils.isBlank(ironTotalPrice)) {
                                errortext += "序号为第" + info.getIdx() + "行数据，铁件含税单价不能为空！";
                            } else {
                                entity.setIronTotalPrice(new BigDecimal(ironTotalPrice));
                                entity.setContractMoney(BigDecimal.ZERO);
                            }
                            String ironTaxTotalPrice = info.getParams().get("ironTaxTotalPrice") != null ? info.getParams().get("ironTaxTotalPrice").toString() : "";
                            if (StringUtils.isBlank(ironTaxTotalPrice)) {
                                errortext += "序号为第" + info.getIdx() + "行数据，铁件含税总价不能为空！";
                            } else {
                                entity.setIronTaxTotalPrice(new BigDecimal(ironTaxTotalPrice));
                            }

                            String area = info.getArea();
                            if (StringUtils.isBlank(area) || StringUtils.isBlank(DictUtils.getDictValue("order_area", area))) {
                                errortext += "序号为第" + info.getIdx() + "行数据，地区不存在或不能为空！";
                            } else {
                                // 地区字典翻译
                                entity.setArea(DictUtils.getDictValue("order_area", area));
                            }

                            Calendar calendar = Calendar.getInstance();
                            entity.setYear(String.valueOf(calendar.get(Calendar.YEAR)));
                            if (StringUtils.isNotBlank(errortext)) {
                                map.put("errorText", errortext);
                                map.put("orderInsertCount", orderInsertCount);
                                map.put("orderUpdateCount", orderUpdateCount);
                                return map;
                            } else {
                                list1.add(entity);
                            }
                        }
                    } else {
                        errortext += "序号为" + info.getIdx() + "行数据，订单编号不能为空，请填写后导入！";
                    }
                }
            }
            if (StringUtils.isBlank(errortext)) {
                for (ProjectBaseInfo info : list1) {
                    info.setGoodsType(BusinessConstants.ORDER_GOODS_TYPE_IRON);
                    // TODO 判断订单是否存在，存在则更新，不存在则插入
                    ProjectBaseInfo projectBaseInfo1 = projectBaseInfoMapper.selectByCode(info.getCode());
                    if (projectBaseInfo1!=null) {
                        info.setId(projectBaseInfo1.getId());
                    } else {
                        orderInsertCount += this.insert(info);
                    }
                }

                OrderIronGoods params  = new OrderIronGoods();
                params.setVersion(order.getVersion());
                List<OrderIronGoods> orderIronGoodsList = orderIronGoodsService.selectList(params);

                // list1 按照 code 分成多个list
                Map<String, List<ProjectBaseInfo>> projectMap = list1.stream().collect(Collectors.groupingBy(ProjectBaseInfo::getCode));
                // 遍历map
                for (Map.Entry<String, List<ProjectBaseInfo>> entry : projectMap.entrySet()) {
                    List<ProjectBaseInfo> projectList = entry.getValue();
                    ProjectBaseInfo projectBaseInfo = projectList.get(0);
                    // 遍历projectList
                    OrderIronRecord orderIronRecord = new OrderIronRecord();
                    orderIronRecord.setOrderId(projectBaseInfo.getId());
                    orderIronRecord.setDeliveryDate(projectBaseInfo.getDeliveryTime());
                    orderIronRecord.setOrderCode(projectBaseInfo.getCode());
                    orderIronRecord.setContacts(projectBaseInfo.getDeliveryPerson());
                    orderIronRecord.setPhone(projectBaseInfo.getDeliveryPersonTel());
                    orderIronRecord.setWeight(projectBaseInfo.getWeight());
                    orderIronRecord.setId(IdUtils.fastSimpleUUID());

                    BigDecimal weight =  BigDecimal.ZERO;
                    BigDecimal money =  BigDecimal.ZERO;
                    List<OrderIronDetail> insertList = new ArrayList<>();
                    for (ProjectBaseInfo project : projectList) {
                        // 存入 存入铁件明细
                        OrderIronDetail orderIronDetail = new OrderIronDetail();
                        String unitWeight = project.getParams().get("unitWeight") != null ? project.getParams().get("unitWeight").toString() : "0";
                        String totalWeight = project.getParams().get("totalWeight") != null ? project.getParams().get("totalWeight").toString() : "0";
                        String unitPrice = project.getParams().get("ironTaxUnitPrice") != null ? project.getParams().get("ironTaxUnitPrice").toString() : "0";
                        String totalPrice = project.getParams().get("ironTaxTotalPrice") != null ? project.getParams().get("ironTaxTotalPrice").toString() : "0";
                        String materialCode = project.getParams().get("materialCode") != null ? project.getParams().get("materialCode").toString() : "";
                        String goodsName = project.getParams().get("goodsName") != null ? project.getParams().get("goodsName").toString() : "";
                        String goodsAmount = project.getParams().get("goodsAmount") != null ? project.getParams().get("goodsAmount").toString() : "0";
                        orderIronDetail.setUnitWeight(new BigDecimal(unitWeight));
                        orderIronDetail.setTotalWeight(new BigDecimal(totalWeight));
                        orderIronDetail.setUnitPrice(new BigDecimal(unitPrice));
                        orderIronDetail.setTotalPrice(new BigDecimal(totalPrice));
                        money = money.add(new BigDecimal(totalPrice));
                        orderIronDetail.setMaterialCode(materialCode);
                        // 查询单重 和总重
                        if (StringUtils.isNotBlank(materialCode)) {
                            // 查询materialCode 是否在 orderIronGoodsList 中
                            for(OrderIronGoods orderIronGoods :orderIronGoodsList){
                                if(StringUtils.isNotBlank(orderIronGoods.getCode()) && orderIronGoods.getCode().equals(materialCode) ){
                                    orderIronDetail.setUnitWeight(orderIronGoods.getWeight());
                                    orderIronDetail.setTotalWeight(orderIronGoods.getWeight().multiply(new BigDecimal(goodsAmount)));
                                    weight = weight.add(orderIronDetail.getTotalWeight());
                                    break;
                                }
                                if(StringUtils.isNotBlank(orderIronGoods.getModel()) && orderIronGoods.getModel().equals(goodsName)){
                                    orderIronDetail.setUnitWeight(orderIronGoods.getWeight());
                                    orderIronDetail.setTotalWeight(orderIronGoods.getWeight().multiply(new BigDecimal(goodsAmount)));
                                    weight = weight.add(orderIronDetail.getTotalWeight());
                                    break;
                                }
                            }
                        }
                        orderIronDetail.setSort(Long.parseLong(project.getIdx()));
                        orderIronDetail.setName(goodsName);
                        orderIronDetail.setAmount(new BigDecimal(goodsAmount));
                        orderIronDetail.setRecordId(orderIronRecord.getId());
                        orderIronDetail.setOrderId(projectBaseInfo.getId());
                        orderIronDetail.setCreateBy(SecurityUtils.getUsername());
                        orderIronDetail.setCreateTime(new Date());
                        orderIronDetail.setId(IdUtils.fastSimpleUUID());
                        ironDetailInsertCount++;
                        insertList.add(orderIronDetail);
                    }
                    orderIronDetailService.insertBatch(insertList);
                    orderIronRecord.setWeight(weight);
                    orderIronRecord.setMoney(money);
                    orderIronRecord.setBuyRemain(money);
                    projectBaseInfo.setContractMoney(projectBaseInfo.getContractMoney().add(money));
                    orderIronRecordService.insert(orderIronRecord);
                    this.update(projectList.get(0));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("errorText", errortext);
        map.put("orderInsertCount", orderInsertCount);
        map.put("orderUpdateCount", orderUpdateCount);
        map.put("ironDetailInsertCount", ironDetailInsertCount);
        return map;
    }

    @Override
    public void exportPro(HttpServletRequest request, HttpServletResponse response, ProjectBaseInfo entity) {
        List<ProjectBaseInfo> list = projectBaseInfoMapper.selectList(entity);
        list.stream().forEach(e->{
            Map<String, Object> map = new HashMap<String, Object>();
            //map.put("status", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, e.getSaleDate()));
            map.put("status", DictUtils.getDictLabel("pro_status", e.getStatus()));
            map.put("area", DictUtils.getDictLabel("order_area", e.getArea()));
            map.put("source", DictUtils.getDictLabel("project_source", e.getSource()));
            map.put("goodsType", DictUtils.getDictLabel("order_goods_type", e.getGoodsType()));
            e.setParams(map);
        });
        String fileName = "销售订单统计列表.xlsx";
        String templateName = "销售订单统计模版.xlsx";
        Map<String, Object> params = new HashMap<>();
        params.put("list", list);
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
    }

}
